<?php

namespace App\Jobs;

use App\Episode;
use App\Show;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Log;
class AssociateShowWithUnsortedEpisode extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    protected $showStdObj;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($showStdObj)
    {
        $this->showStdObj = $showStdObj;
        //var_dump($showStdObj);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->attempts() > 1) {
            $this->delete();
            return;
        }
        if ($this->showStdObj->name_length < 3) {
            return;
        }
        $show_name = $this->showStdObj->name_en;
        $show_name = preg_replace('#\W+#', ' ', $show_name);
        $show_name = trim($show_name);
        $show = Show::find($this->showStdObj->id);

        $keyword = str_replace(' ', '%', $show_name);
        $keyword = '%' . $keyword . '%';
        $epIDs = Episode::where('show_id', '=', 396)->where('raw_name', 'like', $keyword)->get()->pluck(['id']);
        foreach ($epIDs as $item) {
            $ep = Episode::find($item);
            $ep->timestamps = false;
            $ep->show_id = $show->id;
            $ep->save();
        }
        Log::info("SHOW-ID:{$this->showStdObj->id}.SHOW-Name:{$this->showStdObj->name_en}.整理完成");
    }
}
